/*
 * jQuery File Upload Plugin JS Example 8.9.1
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/* global $, window */

$(function () {
    'use strict';

    var file_upload_manager_callback = null;
    var file_upload_manager_return = null;

    //Bind all file uploads for modal popup
    $(document).on('click', '.single-file-upload-manager', function () {
        var upload_url = $(this).attr('data-url');
        var save_to = $(this).attr('data-save_to');
        file_upload_manager_callback = $(this).attr('data-callback');
        var filetypes = $(this).attr('data-filetypes');
        var filesize = $(this).attr('data-max-filesize');
        var image_max_width = $(this).attr('data-image_max_width');
        var image_max_height = $(this).attr('data-image_max_height');
        var number_upload_files = parseInt($(this).attr('data-number_upload_files'));
        var extra_params_callback = $(this).attr('data-extra_params_callback');
        var extra_params = executeFunction(extra_params_callback);
        var params = {
            upload_save_to:save_to,
            upload_filetypes:filetypes,
            upload_maxfilesize:filesize,
            max_width: image_max_width,
            max_height: image_max_height
        };

        var settings = $.extend({}, params, extra_params);
        //show the progress loader
        $('#single-upload-progress').removeClass('hide');

        var file_upl_params = {
            // Uncomment the following to send cross-domain cookies:
            //xhrFields: {withCredentials: true},
            dataType: 'json',
            url: upload_url,
            maxNumberOfFiles:number_upload_files,
            formData: settings,
            maxFileSize: 6000000,
            singleFileUploads: false,
            done: function (e, data) {
                file_upload_manager_return = data.result;
                executeFunction(file_upload_manager_callback,file_upload_manager_return);
                $('#single-upload-progress .progress-bar').css(
                    'width',
                    0 + '%'
                );
                $('#single-upload-progress').addClass('hide');
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#single-upload-progress .progress-bar').css(
                    'width',
                    progress + '%'
                );
            }
        };
        if(typeof image_max_width != 'undefined'){
            file_upl_params['imageMaxWidth'] = image_max_width;
            file_upl_params['disableImageResize'] = false;
            file_upl_params['imageCrop'] = true;  // Force cropped images
        }
        if(typeof image_max_height != 'undefined'){
            file_upl_params['imageMaxHeight'] = image_max_height;
            file_upl_params['disableImageResize'] = false;
            file_upl_params['imageCrop'] = true;  // Force cropped images
        }

        $('#fileupload').fileupload(file_upl_params).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');

        // Enable iframe cross-domain access via redirect option:
        $('#fileupload').fileupload(
            'option',
            'redirect',
            window.location.href.replace(
                /\/[^\/]*$/,
                '/cors/result.html?%s'
            )
        );
    });


   function executeFunctionByName(functionName, context , args ) {

        if( !context ) {
            context = window;
        }

        var args = Array.prototype.slice.call(arguments).splice(2);
        var namespaces = functionName.split(".");
        var func = namespaces.pop();
        for(var i = 0; i < namespaces.length; i++) {
            context = context[namespaces[i]];
        }

        if( !context[func] ) {
            console.log(func + " cannot be found in the " + context + " context");
            return false;
        }

        return context[func].apply(this, args);
    }

    function executeFunction (func , args ) {

        if( func && typeof func == "string" ) {
            return executeFunctionByName(func, window, args);
        }

        else if( func && $.isFunction(func) ) {
            var args = Array.prototype.slice.call(arguments).splice(1);
            return func.apply(this, args);
        }
    }

});